package com.guoranhao.tool.utils;

import java.util.Collection;
import java.util.Map;

/**
 * @author wanggy
 * @Description:
 * @date 2018/4/1612:08
 */
public class StringUtil {

    /**
     * 字符串是否为数字
     * @return true为数字
     */
    public static boolean isNumber(String str) {
        if(isEmpty(str)){
            return false;
        }
        String regex;
        int index = str.indexOf(",");
        // 有逗号等分隔符的数字
        if (index >= 0) {
            regex = "[0-9]+[0-9]*(,[0-9]{3})+(\\.[0-9]+)?";
        } else {
            regex = "[0-9]+[0-9]*(\\.[0-9]+)?";
        }
        return str.matches(regex);
    }

    /**
     * 对象为空(String Map List Set为空)
     * @return true为空
     */
    public static boolean isEmpty(Object object) {
        if (null == object) {
            return true;
        }
        if(object instanceof String){
            return "".equals(((String) object).trim());
        }
        else if(object instanceof Map){
            return ((Map<?, ?>) object).isEmpty();
        }
        else if(object instanceof Collection){
            return ((Collection<?>) object).isEmpty();
        }
        return false;
    }


    /**
     * 对象非空(String Map List Set非空)
     * @return true为非空
     */
    public static boolean isNotEmpty(Object object) {
        return !isEmpty(object);
    }

    /**
     * 非空返回long值 空或出错返回零
     */
    public static long getLong(Object obj) {
        return getLong(obj, 0);
    }

    /**
     * 非空返回String值 空或出错返回默认值
     */
    public static String getString(Object obj, Object defStr) {
        return isEmpty(obj)?String.valueOf(defStr):String.valueOf(obj);
    }

    /**
     * 非空返回long值 空或出错返回默认值
     */
    public static long getLong(Object obj, long defArg) {
        try {
            return Long.parseLong(getString(obj, defArg));
        } catch (NumberFormatException e) {
            return defArg;
        }
    }

    /**
     * 非空返回int值 空或出错返回零
     */
    public static int getInt(Object obj) {
        return getInt(obj, 0);
    }

    /**
     * 非空返回int值 空或出错返回默认值
     */
    public static int getInt(Object obj, int defArg) {
        try {
            return Integer.parseInt(getString(obj, defArg));
        } catch (NumberFormatException e) {
            return defArg;
        }
    }

    /**
     * 非空返回double值 空或出错返回零
     */
    public static double getDouble(Object obj) {
        return getDouble(obj, 0);
    }

    /**
     * 非空返回double值 空或出错返回默认值
     */
    public static double getDouble(Object obj, int defArg) {
        try {
            return Double.parseDouble(getString(obj, defArg));
        } catch (NumberFormatException e) {
            return defArg;
        }
    }

    public static float getFloat(Object obj, float defArg) {
        try {
            return Float.parseFloat(getString(obj, defArg));
        } catch (NumberFormatException e) {
            return defArg;
        }
    }
}
